#include "filehelper.h"
#include <QFile>
#include <QTextStream>
#include <QStandardPaths>
#include <QDir>
#include <QSettings>
#include <QFileInfo>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <QDebug>
#include <QUrl>
#include <QVariantMap>

FileHelper::FileHelper(QObject *parent) : QObject(parent)
{
}

bool FileHelper::write(const QString &path, const QString &data)
{
    QUrl url(path);
    QString filePath;
    if (url.isValid() && url.isLocalFile()) {
        filePath = url.toLocalFile();
    } else {
        filePath = path;
    }

    QFileInfo fileInfo(filePath);
    if (!fileInfo.isAbsolute()) {
        filePath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) + "/" + filePath;
    }
    qDebug() << "Writing to file:" << filePath;

    QFile file(filePath);
    if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QTextStream stream(&file);
        stream << data;
        file.close();
        qDebug() << "Successfully wrote to" << filePath;
        return true;
    }
    qWarning() << "Failed to open file for writing:" << filePath;
    return false;
}

void FileHelper::saveHistory(const QString &historyJson)
{
    QSettings settings;
    settings.setValue("history", historyJson);
}

QString FileHelper::loadHistory()
{
    QSettings settings;
    QString historyString = settings.value("history").toString();
    if (historyString.isEmpty()) {
        return "[]";
    }

    QJsonParseError error;
    QJsonDocument doc = QJsonDocument::fromJson(historyString.toUtf8(), &error);

    if (error.error != QJsonParseError::NoError || !doc.isArray()) {
        // If there's a parsing error or the root is not an array, return an empty array string
        return "[]";
    }

    return historyString;
}

QVariantMap FileHelper::loadUserPrompts()
{
    QSettings settings;
    QString promptsString = settings.value("userPrompts").toString();
    if (promptsString.isEmpty()) {
        return QVariantMap();
    }

    QJsonDocument doc = QJsonDocument::fromJson(promptsString.toUtf8());
    if (doc.isObject()) {
        return doc.object().toVariantMap();
    }

    return QVariantMap();
}

void FileHelper::saveUserPrompt(const QString &category, const QString &prompt)
{
    if (category.isEmpty() || prompt.isEmpty()) {
        return;
    }

    QSettings settings;
    QString promptsString = settings.value("userPrompts").toString();
    QJsonDocument doc = QJsonDocument::fromJson(promptsString.toUtf8());
    QJsonObject promptsObject;

    if (doc.isObject()) {
        promptsObject = doc.object();
    }

    QJsonArray categoryArray = promptsObject.value(category).toArray();

    // 检查是否已存在
    if (!categoryArray.contains(prompt)) {
        categoryArray.append(prompt);
        promptsObject[category] = categoryArray;
        settings.setValue("userPrompts", QString(QJsonDocument(promptsObject).toJson(QJsonDocument::Compact)));
    }
}

void FileHelper::clearUserPrompts()
{
    QSettings settings;
    settings.beginGroup("userPrompts");
    settings.remove("");
    settings.endGroup();
}